mui.init();//页面初始化
//获取本地信息
var my_phone = localStorage.getItem("my_phone");
var user_id = localStorage.getItem("user_id");
//全局变量
var is_realname, status_user, receiver_state, user_phone; //实名状态

var city_leaber = "86";
var cityPicker3 = null;
var phone_type = "domestic";
var mask = mui.createMask(); //遮罩层

//地区
/*三级联动*/
(function($, doc) {
	$.init();
	$.ready(function() {
		/**
		 * 获取对象属性的值
		 * 主要用于过滤三级联动中，可能出现的最低级的数据不存在的情况，实际开发中需要注意这一点；
		 * @param {Object} obj 对象
		 * @param {String} param 属性名
		 */
		var _getParam = function(obj, param) {
			return obj[param] || '';
		};
		if(city_leaber == "86" || city_leaber == "00886") {
			cityPicker3 = new $.PopPicker({
				layer: 3
			});
			cityPicker3.setData(cityData3);
			var showCityPickerButton = doc.getElementById('region-bar');
			var cityResult3 = doc.getElementById('region');
			showCityPickerButton.addEventListener('tap', function(event) {
				cityPicker3.show(function(items) {
					cityResult3.innerText = _getParam(items[0], 'text') + " " + _getParam(items[1], 'text') + " " + _getParam(items[2], 'text');
					var address =  _getParam(items[0], 'text') + "-" + _getParam(items[1], 'text') + "-" + _getParam(items[2], 'text');
					console.log(address);
					localStorage.setItem("user_add", cityResult3.innerText);
					localStorage.setItem("user_add_par", address);
					bizList(address);
					//返回 false 可以阻止选择框的关闭
					//return false;
				});
			}, false);
		}
	});
})(mui, document);


//点击跳转页面
mui('body').on('tap', '.mui-tab-item', function() {
	window.top.location.href = this.href;
	$(this).addClass("mui-active");
});
//底部菜单栏的页面跳转


//去购物车
$(document).on('tap', '#Shopping_Cart', function() {
	if(user_id == null) {
		mui.openWindow({
			url: "../user/login.html",
			createNew: true
		})
	//} else if(status_user == 2) {
		//mui.toast('账户已被限制，请联系平台。');
		//window.top.location.href = '../Shopping_Cart/Shopping_Cart.html';
		//		mui.openWindow({
		//			url: "../user/login.html",
		//			createNew: true
		//		})
//	} else if(!receiver_state) {
//		mui.openWindow({
//			url: '../user/binding_region.html',
//			extras: {
//				my_phone: my_phone,
//				is_realname: is_realname
//			},
//			createNew: true
//		})
//	} else if(!user_phone) {
//		mui.openWindow({
//			url: "../user/certified_cell_phone_num.html",
//			extras: {
//				is_realname: is_realname
//			},
//			createNew: true
//		})
    } else {
		window.top.location.href = '../Shopping_Cart/Shopping_Cart.html';
	}
})
//去个人中心
$(document).on('tap', '#my_user', function() {
	if(user_id == null) {
		mui.openWindow({
			url: "../user/login.html",
			createNew: true
		})
	}
//	else if(status_user == 2) {
//		mui.toast('账户已被限制，请联系平台。');
//		window.top.location.href = '../my/my_user.html';
		//		mui.openWindow({
		//			url: "../user/login.html",
		//			createNew: true
		//		})
//	} else if(!receiver_state) {
//		mui.openWindow({
//			url: '../user/binding_region.html',
//			extras: {
//				my_phone: my_phone,
//				is_realname: is_realname
//			},
//			createNew: true
//		})
//	}
//else if(!user_phone) {
//		mui.openWindow({
//			url: "../user/certified_cell_phone_num.html",
////			extras: {
////				is_realname: is_realname
////			},
//			createNew: true
//		})
//	}
else {
		window.top.location.href = '../my/my_user.html';
	}
})

//商圈列表登录
var limit = 5; //每页条数
var page = 1; //页数
var isOver = false; //是否加载完

//下拉刷新
mui.init({
	pullRefresh: {
		container: "#refreshContainer", //待刷新区域标识，querySelector能定位的css选择器均可，比如：id、.class等
		up: {
			auto: true, // 可选,默认false.自动上拉加载一次
			contentrefresh: "正在加载...", // 可选，正在加载状态时，上拉加载控件上显示的标题内容
			contentnomore: '没有更多的数据了', // 可选，请求完毕若没有更多数据时显示的提醒内容；
			callback: pullupRefresh //加载数据方法 
		}
	}
})

//所属区域商品集合
function itemPartitionList() {
	mui.ajax(user_url + '/business/tradingAreaList', {
		data: {
			"limit": limit,
			"page": page,
			"sign": "string"
		},
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		timeout: 10000, //超时时间设置为10秒；
		headers: {
			'Content-Type': 'application/json'
		},
		success: function(data) {
			if(data.code == 10000) {
				var p = data.total / limit; //总页数
				if(page >= p) { //当前的页数
					isOver = true;
					mui('#refreshContainer').pullRefresh().endPullupToRefresh(true);
					mui.toast("为您更新了商圈" + data.resp.length + "条信息");
				}
				if(isOver == false) {
					page++;
					mui('#refreshContainer').pullRefresh().endPullupToRefresh(true); //停止正在加载
					mui('#refreshContainer').pullRefresh().enablePullupToRefresh(); //显示上拉加载文字
					mui.toast("为您更新了商圈" + data.resp.length + "条信息");
				}
				var html = '';
				if(data.resp.length == 0) {
					$("#refreshContainer").html('<div class="empty">' +
						'<img src="../../images/business.png">' +
						'<p>暂无商家入驻！</p>' +
						'</div>');
				} else {
					for(var i = 0; i < data.resp.length; i++) {
						html += '<div class="business_conent mui-clearfix">';
						html += '<img class="shop_img" width="75" height="75" src="' + data.resp[i].url + data.resp[i].shopFacadePhotos + '" />';
						html += '<ul class="business_conent_list">';
						html += '<li class="business_conent_list_h1">' + data.resp[i].businessName + '</li>';
						html += '<li class="business_conent_list_font">';
						html += '<img class="icon_phoneimg" src="../../images/phone_icon.png" />';
						html += '<a class="phone_a"><span class="business_conent_font">' + data.resp[i].mobile + '</span></a>';
						html += '</li>';
						html += '<li class="business_conent_list_font">';
						html += '<img class="icon_img" src="../../images/position_icon.png" />';
						html += '<span class="business_conent_font2">' + data.resp[i].receiverState + data.resp[i].receiverCity + data.resp[i].receiverDistrict + data.resp[i].detailedAddress + '</span>';
						html += '</li>';
						html += '</ul>';
						html += '</div>';
					}
				}
				$('#trading_area').append(html);
			}
		},
		error: function(xhr, type, errorThrown) { //异常处理；
			console.log(type);
			var error_msg = JSON.parse(xhr.responseText)
			mui.alert(error_msg.msg)
		}
	});

}

function pullupRefresh() {

	setTimeout(function() {
		mui('#refreshContainer').pullRefresh().disablePullupToRefresh(false);
		setTimeout(function() {
//			itemPartitionList(); //ajax 
			mui('#refreshContainer').pullRefresh().endPullupToRefresh((isOver)); //参数为true代表没有更多数据了。
		}, 500);
	}, 500);

}

//判断ios
var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
if(isiOS) {
	$(".mui-scroll-wrapper").css("padding-top", "50px")
}

//点击拨打号码
//$(document).on('tap', '.phone_a', function() {
//	var phone_num = $(this).text();
//	$(this).attr('href:tel', 'dc:' + phone_num)
//})

//二级按钮退出APP
var first = null;
mui.back = function() {
	//首次按键，提示‘再按一次退出应用’
	if(!first) {
		first = new Date().getTime();
		mui.toast('再按一次退出应用');
		setTimeout(function() {
			first = null;
		}, 1000);
	} else {
		if(new Date().getTime() - first < 1000) {
			plus.runtime.quit();
		}
	}
};
//调用userinfo接口获取实名状态
function initPage(){
	var addressVal = $('#region').html();
	var user_add = localStorage.getItem("user_add");
	var user_add_par = localStorage.getItem("user_add_par");	
	console.log(user_add_par);
	if(user_add==null){
		$('.empty').show();
	}
	else{
		$('#region').html(user_add);
		bizList(user_add_par);
		$('.empty').hide();
	}
}
mui("body").on("tap", ".list-itemon", function() {
	plus.nativeUI.showWaiting("加载中...");
	mask.show(); //显示遮罩层
	var commodity_id = $(this).attr("commodity_id");
	//alert(commodity_id)	
	var commodity_id = $(this).attr("commodity_id");	
	mui.openWindow({
		url: "../trading_area/business_detail.html",
		id: "business_detail",
		extras: {
			detailId: commodity_id
		},
		createNew: true,
		waiting: {
			autoShow: false
		}
	}, mask.close());
});
function bizList(val) {
	if(user_id == null){
		mui.openWindow({
			url: "../user/login.html",
			createNew: true
		})
	}
	else{
		plus.nativeUI.showWaiting("加载中...");
		mask.show(); //显示遮罩层
		mui.ajax(user_url + '/api/nearby_shop/shopList', { //查询用户信息接口
			data: {
				"address": val,
				"page": 1,
				"size": 50
			},
			dataType: 'json', //服务器返回json格式数据
			type: 'post', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			success: function(data) {
				console.log(JSON.stringify(data))
				if(data.code == 10000) {
					plus.nativeUI.closeWaiting(); //关闭等待
					mask.close(); //关闭遮罩层
					var html = ""
					var hotShop = data.resp.list;
					if(hotShop==''){
						$('.empty').show();
					}
					else{
						$('.empty').hide();
						for(var i = 0; i < hotShop.length; i++) {
							html += '<div class="business_conent mui-clearfix list-itemon" commodity_id=' + hotShop[i].shop_id + '>'
							html += '<img class="shop_img" src="'+hotShop[i].shop_logo+'" />'
							html += '<ul class="business_conent_list">'
							html += '<li class="business_conent_list_h1">'+hotShop[i].shop_name+'</li>'
							html += '<li class="business_conent_list_font">'
							html += '<span class="business_conent_font2">'+hotShop[i].address_detail+'</span>'
							html += '</li>'
							html += '</ul>'
							html += '<span class="mui-icon mui-icon-forward account_icon"></span>'
							html += '</div>';
						}
						$(".business_conent_big").html(html);
					}					
				}
				else{
					mui.alert(data.msg)
				}
			},
			error: function(xhr, type, errorThrown) { //异常处理；
				console.log(type);
			}
		});		
	}
}

//页面进入执行方法
window.onload = function() {
	mui.plusReady(function() {
		initPage();
		plus.nativeUI.closeWaiting(); //关闭等待
		mask.close(); //关闭遮罩层
	});
}

